<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
  getProvinceCityService,
  publishSceneryService,
  publishHotelService,
  publishRestaurantService
} from '@/apis/travel'
import { useUserStore } from '@/stores/user'
const UserStore = useUserStore()

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  formData: {
    type: Object,
    default: null
  }
})

watch(
  () => props.formData,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      // 将房源相关数据存储在formModel里面
      formModel.value = newValue
      selectedOption.value = [
        formModel.value.province_id,
        formModel.value.city_id
      ]
      imageList.value = formModel.value?.images?.map((item) => {
        return {
          url: item.url
        }
      })
    }
  }
)

const emit = defineEmits(['closeDrawer'])

// 获取表单进行校验
const formRef = ref(null)

// 公共表单字段
const commonModel = ref({
  province_id: '',
  city_id: '',
  name: '',
  address: '',
  introduce: '',
  images: [],
  longitude: '',
  latitude: '',
  opening_time: '',
  price: '',
  rating: '',
  phone: '',
  type: '',
  is_hot: ''
})

// 景点表单
const sceneryModel = ref({
  description: '',
  grade: '',
  preferential_policy: '',
  tips: '',
  traffic: ''
})

// 酒店表单
const hotelModel = ref({
  grade: '',
  living_policy: {
    age: '',
    pet: '',
    time: '',
    method: '',
    license: '',
    children: '',
    breakfast: '',
    price_illustration: ''
  },
  facility: {
    safe_service: {
      monitoring: false,
      first_aid_kit: false,
      access_control: false,
      fire_extinguisher: false
    },
    clean_service: {
      iron: false,
      laundry_room: false,
      clothes_drier: false,
      laundry_service: false
    },
    front_service: {
      vip: false,
      locker: false,
      hour_service: false,
      wake_up_service: false
    },
    public_service: {
      shop: false,
      wifi: false,
      smoke: false,
      elevator: false
    }
  }
})

// 餐厅表单
const restaurantModel = ref({
  delicacy: ''
})

// 表单字段
const formModel = ref({})

// 省市数据
const options = ref([])

// 当前选择的省市数据
const selectedOption = ref([])

// 存储图片列表
const imageList = ref([])

// 需要预览的图片的地址
const dialogImageUrl = ref('')

// 控制图片预览的显示与隐藏
const dialogVisible = ref(false)

const rules = {
  name: {
    required: true,
    message: '请输入名称',
    trigger: 'blur'
  },
  address: {
    required: true,
    message: '请输入地址',
    trigger: 'blur'
  },
  description: {
    required: true,
    message: '请输入描述',
    trigger: 'blur'
  },
  longitude: {
    required: true,
    message: '请输入经度',
    trigger: 'blur'
  },
  latitude: {
    required: true,
    message: '请输入纬度',
    trigger: 'blur'
  },
  opening_time: {
    required: true,
    message: '请输入时间',
    trigger: 'blur'
  },
  price: {
    required: true,
    message: '请输入价格',
    trigger: 'blur'
  },
  rating: {
    required: true,
    message: '请输入评分',
    trigger: 'blur'
  },
  phone: {
    required: true,
    message: '请输入电话',
    trigger: 'blur'
  },
  grade: {
    required: true,
    message: '请选择等级',
    trigger: 'blur'
  },
  type: {
    required: true,
    message: '请选择类型',
    trigger: 'blur'
  },
  introduce: {
    required: true,
    message: '请输入详细介绍',
    trigger: 'blur'
  },
  preferential_policy: {
    required: true,
    message: '请输入景点优待政策',
    trigger: 'blur'
  },
  tips: {
    required: true,
    message: '请输入温馨提示',
    trigger: 'blur'
  },
  traffic: {
    required: true,
    message: '请输入交通信息',
    trigger: 'blur'
  },
  delicacy: {
    required: true,
    message: '请输入特色美食',
    trigger: 'blur'
  },
  is_hot: {
    required: true,
    message: '请选择是否热门',
    trigger: 'blur'
  }
}

// 映射酒店设施键名到显示文本
const displayHotelFacility = computed(() => ({
  safe_service: {
    monitoring: '公共区域监控',
    first_aid_kit: '急救包',
    access_control: '门禁系统',
    fire_extinguisher: '烟雾报警器'
  },
  clean_service: {
    iron: '熨斗',
    laundry_room: '洗衣房',
    clothes_drier: '干洗服务',
    laundry_service: '洗衣服务'
  },
  front_service: {
    vip: 'VIP通道入住',
    locker: '储物柜',
    hour_service: '24小时前台',
    wake_up_service: '叫醒服务'
  },
  public_service: {
    shop: '商场',
    wifi: '公共区WIFI',
    smoke: '吸烟区',
    elevator: '电梯'
  }
}))

// 映射入住政策键名到显示文本
const displayHotelPolicy = computed(() => ({
  age: '年龄限制',
  pet: '宠物',
  time: '入离时间',
  method: '入住方式',
  license: '证件提示',
  children: '儿童',
  breakfast: '早餐',
  price_illustration: '收费说明'
}))

// 处理房源图片相关功能
// 预览图片
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 删除预览的图片
const handleRemove = (file, fileList) => {
  // 从fileList里删除文件
  const index = fileList.indexOf(file)
  if (index !== -1) {
    fileList.splice(index, 1)
  }
}

// 图片上传前添加请求头
const token = computed(() => UserStore.UserList.token)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${token.value}`
}))

// 图片上传前的操作
const beforeUpload = () => {
  if (!token.value) {
    ElMessage.error('请先登录或获取token')
    return false
  }
  return true
}

// 图片上传成功时的操作
const handleSuccess = (response) => {
  if (formModel.value.images) {
    formModel.value.images.push({ url: response.url })
    ElMessage.success('图片上传成功')
  }
}

// 图片上传失败时的操作
const handleError = (error) => {
  ElMessage.error('图片上传失败', error.message)
}

// 获取省份和城市数据
const getProvinceCity = async () => {
  const res = await getProvinceCityService()
  options.value = res.data
}

// 选择省份和城市时触发函数
const handleRegionChange = () => {
  if (selectedOption.value) {
    formModel.value.province_id = selectedOption.value[0]
    formModel.value.city_id = selectedOption.value[1]
  }
}

// 清空表单数据
const clearFormModel = () => {
  formModel.value = {}
  imageList.value = []
  selectedOption.value = []
}

// 发布信息数据
const publishInfoData = async () => {
  await formRef.value.validate()

  switch (props.type) {
    case '景点':
      await publishSceneryService(formModel.value)
      break
    case '酒店':
      await publishHotelService(formModel.value)
      break
    case '餐厅':
      await publishRestaurantService(formModel.value)
      break
  }
  ElMessage.success(`发布${props.type}成功`)

  // 清空表单
  clearFormModel()
  // 关闭抽屉
  emit('closeDrawer')
}

onMounted(() => {
  getProvinceCity()

  switch (props.type) {
    case '景点':
      formModel.value = { ...commonModel.value, ...sceneryModel.value }
      break
    case '酒店':
      formModel.value = { ...commonModel.value, ...hotelModel.value }
      break
    case '餐厅':
      formModel.value = { ...commonModel.value, ...restaurantModel.value }
      break
  }
})

defineExpose({
  clearFormModel
})
</script>

<template>
  <div>
    <el-form
      class="form"
      autocomplete="off"
      label-width="120"
      size="large"
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item :label="type + '名称'" prop="name">
        <el-input
          v-model.trim="formModel.name"
          placeholder="请输入名称"
        ></el-input>
      </el-form-item>

      <el-form-item :label="type + '地址'" prop="address">
        <el-input
          v-model.trim="formModel.address"
          placeholder="请输入地址"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="type === '景点'"
        :label="type + '描述'"
        prop="description"
      >
        <el-input
          v-model.trim="formModel.description"
          placeholder="请输入景点描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="省市">
        <el-cascader
          v-model="selectedOption"
          :options="options"
          clearable
          placeholder="请选择省市"
          @change="handleRegionChange"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="经度" prop="longitude">
        <el-input
          type="number"
          v-model.trim="formModel.longitude"
          placeholder="请输入经度"
        ></el-input>
      </el-form-item>

      <el-form-item label="纬度" prop="latitude">
        <el-input
          type="number"
          v-model.trim="formModel.latitude"
          placeholder="请输入纬度"
        ></el-input>
      </el-form-item>

      <el-form-item
        :label="
          type === '景点'
            ? '开放时间'
            : type === '酒店'
              ? '开业时间'
              : '营业时间'
        "
        prop="opening_time"
      >
        <el-input
          v-model.number="formModel.opening_time"
          placeholder="请输入时间"
        ></el-input>
      </el-form-item>

      <el-form-item :label="type + '价格'" prop="price">
        <el-input
          type="number"
          v-model.trim="formModel.price"
          placeholder="请输入价格"
        ></el-input>
      </el-form-item>

      <el-form-item :label="type + '评分'" prop="rating">
        <el-input
          type="number"
          v-model.trim="formModel.rating"
          placeholder="请输入评分"
        ></el-input>
      </el-form-item>

      <el-form-item :label="type + '电话'" prop="phone">
        <el-input
          v-model.trim="formModel.phone"
          placeholder="请输入电话"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="type !== '餐厅'" :label="type + '等级'" prop="grade">
        <el-select
          v-model="formModel.grade"
          placeholder="请选择等级"
          style="width: 240px"
        >
          <el-option
            :label="type === '景点' ? '5A' : '5星'"
            :value="type === '景点' ? '5A' : '5星'"
          />
          <el-option
            :label="type === '景点' ? '4A' : '4星'"
            :value="type === '景点' ? '4A' : '4星'"
          />
          <el-option
            :label="type === '景点' ? '3A' : '3星'"
            :value="type === '景点' ? '3A' : '3星'"
          />
          <el-option
            :label="type === '景点' ? '2A' : '2星'"
            :value="type === '景点' ? '2A' : '2星'"
          />
          <el-option
            :label="type === '景点' ? '1A' : '1星'"
            :value="type === '景点' ? '1A' : '1星'"
          />
          <el-option :label="'普通' + type" :value="'普通' + type" />
        </el-select>
      </el-form-item>

      <el-form-item :label="type + '类型'" prop="type">
        <el-select
          v-model="formModel.type"
          placeholder="请选择类型"
          style="width: 240px"
        >
          <el-option
            :label="
              type === '景点' ? '城市观光' : type === '酒店' ? '经济型' : '中餐'
            "
            :value="
              type === '景点' ? '城市观光' : type === '酒店' ? '经济型' : '中餐'
            "
          />
          <el-option
            :label="
              type === '景点' ? '人文古迹' : type === '酒店' ? '特惠型' : '西餐'
            "
            :value="
              type === '景点' ? '人文古迹' : type === '酒店' ? '特惠型' : '西餐'
            "
          />
          <el-option
            :label="
              type === '景点'
                ? '自然风光'
                : type === '酒店'
                  ? '豪华型'
                  : '特色小吃'
            "
            :value="
              type === '景点'
                ? '自然风光'
                : type === '酒店'
                  ? '豪华型'
                  : '特色小吃'
            "
          />
          <el-option
            :label="
              type === '景点' ? '网红打卡' : type === '酒店' ? '民宿' : '自助餐'
            "
            :value="
              type === '景点' ? '网红打卡' : type === '酒店' ? '民宿' : '自助餐'
            "
          />
          <el-option
            :label="
              type === '景点' ? '展览展馆' : type === '酒店' ? '公寓' : '快餐'
            "
            :value="
              type === '景点' ? '展览展馆' : type === '酒店' ? '公寓' : '快餐'
            "
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="type + '详细介绍'" prop="introduce">
        <el-input
          autosize
          type="textarea"
          v-model.trim="formModel.introduce"
          placeholder="请输入详细介绍"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="type === '餐厅'" label="特色美食" prop="delicacy">
        <el-input
          autosize
          type="textarea"
          v-model.trim="formModel.delicacy"
          placeholder="请输入特色美食"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="type === '景点'"
        label="景点优待政策"
        prop="preferential_policy"
      >
        <el-input
          autosize
          type="textarea"
          v-model.trim="formModel.preferential_policy"
          placeholder="请输入景点优待政策"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="type === '景点'" label="温馨提示" prop="tips">
        <el-input
          autosize
          type="textarea"
          v-model.trim="formModel.tips"
          placeholder="请输入温馨提示"
        ></el-input>
      </el-form-item>

      <el-form-item v-if="type === '景点'" label="交通信息" prop="traffic">
        <el-input
          autosize
          type="textarea"
          v-model.trim="formModel.traffic"
          placeholder="请输入交通信息"
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="type === '酒店' && formModel.living_policy"
        label="入住政策"
        prop="living_policy"
      >
        <el-input
          style="margin-bottom: 20px"
          v-for="(label, key) in displayHotelPolicy"
          :key="key"
          autosize
          v-model.trim="formModel.living_policy[key]"
          :placeholder="'请输入' + label"
        >
          <template #prepend>{{ label }}</template></el-input
        >
      </el-form-item>

      <el-form-item
        label="酒店设施"
        v-if="type === '酒店' && formModel.facility"
      >
        <el-checkbox
          v-for="(label, key) in displayHotelFacility.safe_service"
          :key="key"
          :label="key"
          v-model="formModel.facility.safe_service[key]"
        >
          {{ label }}
        </el-checkbox>

        <el-checkbox
          v-for="(label, key) in displayHotelFacility.clean_service"
          :key="key"
          :label="key"
          v-model="formModel.facility.clean_service[key]"
        >
          {{ label }}
        </el-checkbox>

        <el-checkbox
          v-for="(label, key) in displayHotelFacility.front_service"
          :key="key"
          :label="key"
          v-model="formModel.facility.front_service[key]"
        >
          {{ label }}
        </el-checkbox>

        <el-checkbox
          v-for="(label, key) in displayHotelFacility.public_service"
          :key="key"
          :label="key"
          v-model="formModel.facility.public_service[key]"
        >
          {{ label }}
        </el-checkbox>
      </el-form-item>

      <el-form-item :label="'热门' + type" prop="is_hot">
        <el-select
          v-model="formModel.is_hot"
          placeholder="请选择是否热门"
          style="width: 240px"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item :label="type + '图片'">
        <!-- 图片上传 -->
        <el-upload
          v-model:file-list="imageList"
          :action="`https://www.u2051641.nyat.app:64347/api/${type === '景点' ? 'scenery' : type === '酒店' ? 'hotel' : 'restaurant'}/upload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :headers="uploadHeaders"
          :on-success="handleSuccess"
          :on-error="handleError"
          multiple="true"
        >
          <el-icon><i-ep-Plus></i-ep-Plus></el-icon>
        </el-upload>

        <!-- 图片预览 -->
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="large" @click="publishInfoData">
          <template #icon>
            <el-icon>
              <i-ep-Position></i-ep-Position>
            </el-icon>
          </template>
          <template #default>发布</template>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
